package service

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"log"
	"math/rand"
	"service/basic/config"
	__ "service/basic/proto"
	"service/handler/model"
	"service/untils"
	"strconv"
	"time"
)

// 预约单
func (s *Server) Reservation(_ context.Context, in *__.ReservationReq) (*__.ReservationResp, error) {
	var reservation model.Order
	//获取当前时间戳
	dataTime := time.Now().Unix()
	data := strconv.Itoa(int(dataTime))
	//转换用户id为字符串
	uId := strconv.Itoa(int(in.UserId))
	reservation.OrderNo = uuid.NewString() + data + uId
	reservation.UserId = uint(in.UserId)
	reservation.Address = in.Address
	reservation.CleanerAre = uint(in.CleanerAre)
	reservation.ClearanerType = in.CleanerType
	diff := rand.Intn(10) + 1 //难度系数
	reservation.Diff = uint(diff)
	//计算价格
	if in.CleanerType == "日常清洁" {
		reservation.PriceCount = uint(config.DAILY_FOUNDATION + (in.CleanerAre-10)*config.DAILY_FOUNDATIONS)
	}
	if in.CleanerType == "深度清洁" {
		reservation.PriceCount = uint(config.DEPTH_FOUNDATION + (in.CleanerAre-10)*config.DEPTH_FOUNDATIONS)
	}
	if in.CleanerType == "开荒清洁" {
		reservation.PriceCount = uint(config.STRONG_FOUNDATION + (in.CleanerAre-10)*config.STRONG_FOUNDATIONS)
	}
	log.Println(uint(config.DAILY_FOUNDATION + (in.CleanerAre-10)*config.DAILY_FOUNDATIONS))
	//预约单生成
	if err := reservation.Create(); err != nil {
		return nil, errors.New("预约单生成失败")
	}

	//存入redis
	marshal, err := json.Marshal(&reservation)
	if err != nil {
		return nil, errors.New("预约信息序列化失败")
	}
	key := fmt.Sprintf("reservation: %d", in.UserId)
	config.Rdb.Set(config.Ctx, key, marshal, time.Hour)

	//同步到es
	es := untils.Es{
		Index: "reservation",
		Id:    int64(reservation.Id),
		Body:  &reservation,
	}
	es.SyncData()

	//实例化rabbitmq
	rabbitmq := untils.NewRabbitMQSimple(untils.MQURL)
	_, err = rabbitmq.PublishSimple(reservation.OrderNo)
	if err != nil {
		return nil, errors.New("消息发送失败")
	}
	log.Println(fmt.Sprintf("消息发送成功: %v", reservation.OrderNo))

	return &__.ReservationResp{
		CleanerCount: int64(reservation.PriceCount),
	}, nil
}

// 查询订单记录
func (s *Server) OrderList(_ context.Context, in *__.OrderListReq) (*__.OrderListResp, error) {
	var order model.Order
	order.PayStatus = uint(in.PayStatus)
	orderList, err := order.List()
	if err != nil {
		return nil, errors.New("订单查询失败")
	}

	var orderLists []*__.OrderList
	for _, o := range orderList {
		list := __.OrderList{
			Id:          int64(o.Id),
			OrderNo:     o.OrderNo,
			UserId:      int64(o.UserId),
			CleanerId:   int64(o.CleanerId),
			Address:     o.Address,
			CleanerAre:  int64(o.CleanerAre),
			Diff:        int64(o.Diff),
			CleanerType: o.ClearanerType,
			PriceCount:  int64(o.PriceCount),
		}
		orderLists = append(orderLists, &list)
	}

	return &__.OrderListResp{
		List: orderLists,
	}, nil
}
